package com.hzw.saas.web.app.im.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hzw.saas.api.chat.IChatEventService;
import com.hzw.saas.api.chat.IChatGroupService;
import com.hzw.saas.api.chat.IChatUserGroupService;
import com.hzw.saas.api.chat.bo.ChatEventBO;
import com.hzw.saas.api.chat.bo.ChatGroupBO;
import com.hzw.saas.api.chat.bo.ChatUserGroupBO;
import com.hzw.saas.api.chat.bo.SingleGroupBO;
import com.hzw.saas.api.user.ICustomerService;
import com.hzw.saas.api.user.export.UserRegisterBO;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.security.utils.SecurityUtils;
import com.hzw.saas.common.util.MapperUtil;
import com.hzw.saas.common.util.SnowFlakeUtil;
import com.hzw.saas.web.app.im.param.GroupParam;
import com.hzw.saas.web.app.im.param.GroupUserParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(tags = "Chat")
@RequestMapping("/chat")
public class ChatController {

    @Resource(name = "chatEventService")
    private IChatEventService chatEventService;

    @Resource(name = "chatGroupService")
    private IChatGroupService chatGroupService;

    @Resource(name = "chatUserGroupService")
    private IChatUserGroupService chatUserGroupService;

    @Resource
    private ICustomerService customerService;

    @ApiOperationSort(1)
    @PostMapping("/group/add/group")
    @SysLog(operation = "创建群组")
    @ApiOperation(value = "创建群组")
    public ResponseEntity<Void> addGroup(@RequestBody @Valid GroupParam param) {
        String userId = SecurityUtils.getUser().getUserId();
        SingleGroupBO map = MapperUtil.nf().map(param, SingleGroupBO.class);
        map.setGroupId(SnowFlakeUtil.nextIdStr());
        ArrayList<SingleGroupBO> singleGroupBOS = new ArrayList<>();
        singleGroupBOS.add(map);
        chatGroupService.addGroup(userId, singleGroupBOS, 2);
        //群组中添加群主
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(2)
    @PostMapping("/group/add/user")
    @SysLog(operation = "群组同意加人")
    @ApiOperation(value = "群组同意加人")
    public ResponseEntity<Void> addUser(@RequestBody @Valid GroupUserParam param) {
        String userId = SecurityUtils.getUser().getUserId();
        List<ChatUserGroupBO> byUserIdAndGroup = chatUserGroupService.findByUserIdAndGroup(param.getGroupId(), param.getUserId());
        AssertUtil.assertThrow("找不到用户数据", CollectionUtil.isEmpty(byUserIdAndGroup));
        List<ChatUserGroupBO> collect = byUserIdAndGroup.stream().filter(o -> o.getPermission().equals(0)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(collect)) {
            return ResponseEntity.ok().build();
        }
        ChatUserGroupBO chatUserGroupBO = collect.get(0);
        chatUserGroupBO.setPermission(1);
        ArrayList<ChatUserGroupBO> chatUserGroupBOS = new ArrayList<>();
        chatUserGroupBOS.add(chatUserGroupBO);
        chatUserGroupService.updateBatch(chatUserGroupBOS);
        //触发加人事件
        chatUserGroupService.changeUserGroupEvent(userId, param.getUserId(), param.getGroupId());
        return ResponseEntity.ok().build();
    }

    @ApiOperationSort(3)
    @GetMapping("/group/chat/list")
    @SysLog(operation = "查询聊天列表的近期聊天记录")
    @ApiOperation(value = "查询聊天列表的近期聊天记录")
    public ResponseEntity<IPage<ChatEventBO>> findLatestMsg(PageParam pageParam) {
        IPage<ChatEventBO> latestMsg = chatEventService.findLatestMsg(SecurityUtils.getUser().getUserId(), pageParam);
        List<ChatEventBO> records = latestMsg.getRecords();
        List<ChatEventBO> name = findName(records);
        latestMsg.setRecords(name);
        return ResponseEntity.ok(latestMsg);
    }

    @ApiOperationSort(3)
    @GetMapping("/group/chat/{group}")
    @SysLog(operation = "查询指定群聊天记录")
    @ApiOperation(value = "查询指定群聊天记录")
    public ResponseEntity<IPage<ChatEventBO>> findHistoryByUserId(@PathVariable("group") String group, PageParam pageParam) {
        IPage<ChatEventBO> historyByUserId = chatEventService.findHistoryByUserId(SecurityUtils.getUser().getUserId(), group, pageParam);
        List<ChatEventBO> records = historyByUserId.getRecords();
        List<ChatEventBO> name = findName(records);
        historyByUserId.setRecords(name);
        return ResponseEntity.ok(historyByUserId);
    }

    List<ChatEventBO> findName(List<ChatEventBO> chatEventBOS) {
        if (CollectionUtil.isNotEmpty(chatEventBOS)) {
            List<String> userInfo = chatEventBOS.stream().map(ChatEventBO::getSourceId).collect(Collectors.toList());
            List<String> groupInfo = chatEventBOS.stream().map(ChatEventBO::getTargetGroupId).collect(Collectors.toList());

//            List<UserProfileBO> byUserIds = userProfileService.getUserProfiles(userInfo);
            List<ChatGroupBO> byIds = chatGroupService.findByIds(groupInfo);
            List<UserRegisterBO> byUserIds = customerService.findByUserIds(userInfo);
            chatEventBOS.forEach(chatEventBO -> {
                byUserIds.forEach(userRegisterBO -> {
                    if (chatEventBO.getSourceId().equals(userRegisterBO.getUserId())) {
                        chatEventBO.setSourceName(userRegisterBO.getCustomerName());
                    }
                });

                byIds.forEach(chatGroupBO -> {
                    if (chatEventBO.getTargetGroupId().equals(chatGroupBO.getPid())) {
                        chatEventBO.setGroupName(chatGroupBO.getGroupName());
                    }
                });
            });
        }
        return chatEventBOS;
    }

    @ApiOperationSort(3)
    @GetMapping("/group/chat/members/{groupId}")
    @SysLog(operation = "查找群组人数")
    @ApiOperation(value = "查找群组人数")
    public ResponseEntity<Integer> memberNum(@PathVariable("groupId") String groupId) {
        List<ChatUserGroupBO> usersByGroupId = chatUserGroupService.findUsersByGroupId(groupId);
        if (CollectionUtil.isEmpty(usersByGroupId)) {
            return ResponseEntity.ok(0);
        }
        return ResponseEntity.ok(usersByGroupId.size());
    }

}
